﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace StoneStorage
{
    public partial class InvoiceForm : Form
    {
        public MyInvoice Invoice
        {
            get;
            private set;
        }

        private StoneStorageDataSet dataSet;
        private BusinessRules bRules;
        private InvoiceKindEnum invoiceKind;

        private InvoiceForm()
        {
            InitializeComponent();
        }

        public InvoiceForm(StoneStorageDataSet dSet, InvoiceKindEnum kind)
            : this()
        {
            if (dSet == null)
            {
                throw new ArgumentNullException("dSet");
            }
            if (!(kind == InvoiceKindEnum.Expenditure) && !(kind == InvoiceKindEnum.Income))
            {
                throw new InvalidOperationException("Не известен тип накладной");
            }

            this.dataSet = dSet;
            this.invoiceKind = kind;
            this.bRules = new BusinessRules(this.dataSet);
            this.Invoice = new MyInvoice();
            
            if (kind == InvoiceKindEnum.Income)
            {
                this.Text = "Приходная " + this.Text;
                this.lNumber.Text = "Приходная " + this.lNumber.Text;
            }
            if (kind == InvoiceKindEnum.Expenditure)
            {
                this.Text = "Расходная " + this.Text;
                this.lNumber.Text = "Расходная " + this.lNumber.Text;
            }

            this.LoadToDgvInvoice(dSet);
            CreateNumber(kind);
        }

        private void CreateNumber(InvoiceKindEnum kind)
        {
            int number = 0;

            if (kind == InvoiceKindEnum.Income)
            {
                number = bRules.CreateInvoiceNumber(dataSet.IncomeInvoiceData.NumberColumn,
                    dataSet.IncomeInvoiceData.DateColumn,
                    this.dtpDate.Value);
            }
            if (kind == InvoiceKindEnum.Expenditure)
            {
                number = bRules.CreateInvoiceNumber(dataSet.ExpenditureInvoiceData.NumberColumn,
                    dataSet.ExpenditureInvoiceData.DateColumn,
                    this.dtpDate.Value);
            }

            this.tbNumber.Text = number.ToString();
        }

        private void LoadToDgvInvoice(StoneStorageDataSet dSet)
        {
            BindingSource itemsBSource = new BindingSource();
            itemsBSource.DataSource = Invoice.Items;
            dgvInvoice.AutoGenerateColumns = false;
            dgvInvoice.DataSource = itemsBSource;

            BindingSource stoneBSource = new BindingSource();
            BindingSource producerBSource = new BindingSource();

            stoneBSource.DataSource = dSet.StoneDictionary;
            producerBSource.DataSource = dSet.ProducerDictionary;

            // Создание колонки Вид камня

            DataGridViewComboBoxColumn comboColumn1 = new DataGridViewComboBoxColumn();
            comboColumn1.HeaderText = "Вид камня";
            comboColumn1.Name = "stoneColumn";
            comboColumn1.DataSource = stoneBSource;
            comboColumn1.DataPropertyName = "StoneId";
            comboColumn1.ValueMember = "Id";
            comboColumn1.DisplayMember = "Name";
            comboColumn1.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dgvInvoice.Columns.Add(comboColumn1);

            // Создание колонки Производитель

            DataGridViewComboBoxColumn comboColumn2 = new DataGridViewComboBoxColumn();
            comboColumn2.HeaderText = "Производитель";
            comboColumn2.Name = "producerColumn";
            comboColumn2.DataSource = producerBSource;
            comboColumn2.DataPropertyName = "ProducerId";
            comboColumn2.ValueMember = "Id";
            comboColumn2.DisplayMember = "Name";
            comboColumn2.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dgvInvoice.Columns.Add(comboColumn2);

            // Создание колонки Длина

            DataGridViewTextBoxColumn length = new DataGridViewTextBoxColumn();
            length.HeaderText = "Длина, см.";
            length.Name = "lengthColumn";
            length.DataPropertyName = "Length";
            dgvInvoice.Columns.Add(length);

            // Создание колонки Ширина

            DataGridViewTextBoxColumn width = new DataGridViewTextBoxColumn();
            width.HeaderText = "Ширина, см.";
            width.Name = "widthColumn";
            width.DataPropertyName = "Width";
            dgvInvoice.Columns.Add(width);

            // Создание колонки Высота

            DataGridViewTextBoxColumn height = new DataGridViewTextBoxColumn();
            height.HeaderText = "Высота, см.";
            height.Name = "heightColumn";
            height.DataPropertyName = "Height";
            dgvInvoice.Columns.Add(height);

            // Создание колонки Количество

            DataGridViewTextBoxColumn Count = new DataGridViewTextBoxColumn();
            Count.HeaderText = "Количество";
            Count.Name = "CountColumn";
            Count.DataPropertyName = "Count";
            dgvInvoice.Columns.Add(Count);
        }

        private void bOk_Click(object sender, EventArgs e)
        {
            if (this.tbDeliverer.Text == "")
            {
                throw new InvalidOperationException("Не указан отправитель.");
            }

            if (this.tbAccepter.Text == "")
            {
                throw new InvalidOperationException("Не указан приемщик.");
            }

            Invoice.Number = Convert.ToInt32(this.tbNumber.Text);
            Invoice.Date = Convert.ToDateTime(this.dtpDate.Text);
            Invoice.Deliverer = this.tbDeliverer.Text;
            Invoice.Accepter = this.tbAccepter.Text;

            try
            {
                bRules.CheckInvoice(this.Invoice);
            }
            catch (InvalidInvoiceException ex)
            {
                dgvInvoice.CurrentCell = dgvInvoice.Rows[Invoice.Items.IndexOf(ex.Item)].Cells["stoneColumn"];
                dgvInvoice.Rows[Invoice.Items.IndexOf(ex.Item)].Selected = true;
                throw;
            }

            if (invoiceKind == InvoiceKindEnum.Expenditure)
            {
                try
                {
                    bRules.CheckExpenditureInvoiceItem(Invoice);
                }
                catch (InvalidInvoiceException ex)
                {
                    dgvInvoice.CurrentCell = dgvInvoice.Rows[Invoice.Items.IndexOf(ex.Item)].Cells["CountColumn"];
                    dgvInvoice.Rows[Invoice.Items.IndexOf(ex.Item)].Selected = true;
                    throw;
                }
            }

            this.DialogResult = DialogResult.OK;
        }

        private void bCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dtpDate_Leave(object sender, EventArgs e)
        {
            this.CreateNumber(invoiceKind);
        }
    }
}
